package com.example.springboot.controller.guava;

import com.google.common.collect.HashMultimap;
import com.google.common.collect.Multimap;
import com.google.common.collect.Multimaps;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.context.request.async.DeferredResult;

import java.util.Collection;
import java.util.Date;

/**
 * java长轮询实现消息推送
 *
 * @Author:ChenZhangKun
 * @Date: 2022/8/23 12:36
 */
@RestController
@RequestMapping("/long/pull")
public class LongPullingController {
    // 存放监听某个Id的长轮询集合
    // 线程同步结构
    private static Multimap<String, DeferredResult<String>> watchRequests = Multimaps.synchronizedMultimap(HashMultimap.create());
    private static final Long TIME_OUT = 60 * 1000 * 100L;


    /**
     * 设置监听
     * 阻塞
     *
     * @param id
     * @return
     */
    @GetMapping("watch/{id}")
    public DeferredResult<String> watch(@PathVariable("id") String id) {
        // 延迟对象设置超时时间
        DeferredResult<String> deferredResult = new DeferredResult<>(TIME_OUT);
        // 异步请求完成时移除 key，防止内存溢出
        deferredResult.onCompletion(() -> {
            watchRequests.remove(id, deferredResult);
        });
        watchRequests.put(id, deferredResult);
        return deferredResult;
    }

    /**
     * 实现消息推送
     *
     * @param id
     * @return
     */
    @GetMapping("/publish/{id}")
    public String publish(@PathVariable("id") String id) {
        if (watchRequests.containsKey(id)) {
            Collection<DeferredResult<String>> deferredResults = watchRequests.get(id);
            for (DeferredResult<String> deferredResult : deferredResults) {
                deferredResult.setResult("更新了" + new Date());
            }
        }
        return "success";
    }

}
